package io.unicorn.modules.water.controller;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qiniu.util.StringUtils;
import io.unicorn.common.annotation.SysLog;
import io.unicorn.common.excelutils.ExcelListener;
import io.unicorn.common.exception.RRException;
import io.unicorn.common.utils.DateUtils;
import io.unicorn.common.utils.ExcelUtils;
import io.unicorn.common.validator.ValidatorUtils;
import io.unicorn.modules.progress.entity.ProgressSingleton;
import io.unicorn.modules.water.dao.TDeviceInfoDao;
import io.unicorn.modules.water.entity.TAccountManageEntity;
import io.unicorn.modules.water.entity.TDeviceInfoEntity;
import io.unicorn.modules.water.service.TDeviceInfoService;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import io.unicorn.modules.water.entity.TClientInfoEntity;
import io.unicorn.modules.water.service.TClientInfoService;
import io.unicorn.common.utils.PageUtils;
import io.unicorn.common.utils.R;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * ${comments}
 *
 * @author LNCG
 * @email LNCG@USTL.EDU.CN
 * @date 2021-05-03 08:18:00
 */
@RestController
@RequestMapping("water/tclientinfo")
public class TClientInfoController {
    @Autowired
    private TClientInfoService tClientInfoService;
    @Autowired
    private TDeviceInfoService tDeviceInfoService;
    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("water:tclientinfo:list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = tClientInfoService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{deviceId}")
    @RequiresPermissions("water:tclientinfo:info")
    public R info(@PathVariable("deviceId") String deviceId){
        TClientInfoEntity tClientInfo = tClientInfoService.getById(deviceId);

        return R.ok().put("tClientInfo", tClientInfo);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("water:tclientinfo:save")
    public R save(@RequestBody TClientInfoEntity tClientInfo){
        tClientInfoService.save(tClientInfo);

        return R.ok();
    }

    /**
     * 修改
     */
    //@SysLog("修改用户信息")
    @RequestMapping("/update")
    @RequiresPermissions("water:tclientinfo:update")
    public R update(@RequestBody TClientInfoEntity tClientInfo){
        ValidatorUtils.validateEntity(tClientInfo);
        tClientInfoService.updateById(tClientInfo);
        
        return R.ok();
    }

    /**
     * 2023.11.19
     * 售后服务只更新：工程部 刘祥林，张旭东，喻实，马东辉，王宏，李生金，陈广野，于洋，这8个人，查询，可以修改，现场记录，表盘号，表封号就行
     * @param tClientInfo
     * @return
     */

    @SysLog("维护用户信息")
    @RequestMapping("/update1")
    @RequiresPermissions("water:tclientinfo:update1")
    public R update1(@RequestBody TClientInfoEntity tClientInfo){
        ValidatorUtils.validateEntity(tClientInfo);
        tClientInfoService.updateById(tClientInfo);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("water:tclientinfo:delete")
    public R delete(@RequestBody String[] deviceIds){
        tClientInfoService.removeByIds(Arrays.asList(deviceIds));

        return R.ok();
    }

    @RequestMapping("/export")
    @RequiresPermissions("water:tclientinfo:list")
    public void export(@RequestParam Map<String, Object> params,
                       HttpServletRequest request,
                       HttpServletResponse repsonse){
        JSONObject jsonObject = JSONObject.parseObject((String)params.get("params"));
        PageUtils page = tClientInfoService.queryPage(jsonObject);
        List<?> listEntity = page.getList();
        String deptId = (String)jsonObject.get("dept");
        if (StringUtils.isNullOrEmpty(deptId)) deptId = "";
        ExcelUtils.exportXlsx(
                repsonse,
                "export_"+deptId,
                "io.unicorn.modules.water.entity.TClientInfoEntity",
                listEntity);
    }

    @RequestMapping("/downloadtemplate")
    public void genExcelTemplate(
            @RequestParam Map<String, Object> params,
            HttpServletResponse response) throws IOException {
        JSONObject jsonObject = JSONObject.parseObject((String)params.get("params"));
        String strTemplateName = "template";
        if (!StringUtils.isNullOrEmpty((String)jsonObject.get("dept"))){
            strTemplateName += "_" + jsonObject.get("dept");
        }
        strTemplateName += ".xlsx";
        byte[] data = tClientInfoService.genExcelTemplate(jsonObject);

        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\""+ URLEncoder.encode(strTemplateName,"UTF-8")+"\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");

        IOUtils.write(data, response.getOutputStream());
    }

    @PostMapping("/importExcel")
    @RequiresPermissions("water:tclientinfo:update")
    public R importExcel(@RequestParam("myfile") MultipartFile myFile,HttpServletRequest request,HttpServletResponse response){
        if (myFile.isEmpty()) {
            throw new RRException("上传文件不能为空");
        }
        String fileName = myFile.getOriginalFilename();//  获取文件名
        //String suffix = myFile.getOriginalFilename().substring(myFile.getOriginalFilename().lastIndexOf("."));
        //Integer nums = meterArchivesService.importExcel(myFile);

        String id = request.getSession().getId() + fileName;
        AtomicReference<Integer> progress = new AtomicReference<>(0);
        ProgressSingleton.put(id + "Progress", progress);

        try {
            EasyExcel.read(myFile.getInputStream(), TClientInfoEntity.class, new ExcelListener(p -> {
                //保存逻辑（可封装一个普通的sevice）p-为我们执行函数时传入的list
                //sendAddressService.importExcel(p);

                //检查是否有IMEI重复
                //List <String> listIMEI = tClientInfoService

                List <TDeviceInfoEntity> listDataDevice = new ArrayList<>();
                p.stream().forEach(obj->{
                    ((TClientInfoEntity)obj).setDesc20(DateUtils.format(new Date(),DateUtils.DATE_TIME_PATTERN));

                    TDeviceInfoEntity item = new TDeviceInfoEntity();
                    item.setDeviceId(((TClientInfoEntity) obj).getDeviceId());
                    item.setNeiName(((TClientInfoEntity) obj).getMemo1());
                    //更新类型，不能是煤气表，直接查询 类型0
                    //item.setTypeId(7);

                    item.setMemo3(DateUtils.format(new Date(),DateUtils.DATE_TIME_PATTERN));

                    try {
                        item.setMasterNum(Integer.parseInt(((TClientInfoEntity) obj).getDesc11()));
                    } catch (Exception ex) {
                        item.setMasterNum(0);
                    }
                    try {
                        item.setSlaveNum(Integer.parseInt(((TClientInfoEntity) obj).getDesc12()));
                    } catch (Exception ex) {
                        item.setSlaveNum(0);
                    }
                    try {
                        item.setCardNum(Integer.parseInt(((TClientInfoEntity) obj).getDesc13()));
                    } catch (Exception ex) {
                        item.setCardNum(0);
                    }
                    try {
                        item.setRouteNum(Integer.parseInt(((TClientInfoEntity) obj).getDesc14()));
                    } catch (Exception ex) {
                        item.setRouteNum(0);
                    }
                    try {
                        item.setMeterNum(Integer.parseInt(((TClientInfoEntity) obj).getDesc15()));
                    } catch (Exception ex) {
                        item.setMeterNum(0);
                    }

                    progress.getAndSet(progress.get() + 1);
                    ProgressSingleton.put(id + "Progress", progress);

                    listDataDevice.add(item);
                });

                try {
                   tClientInfoService.saveOrUpdateBatch(p);
                   if (listDataDevice.size() > 0){
                       tDeviceInfoService.saveOrUpdateBatch(listDataDevice);
                   }
                }catch(Exception e){
                    throw new RRException(e.toString(),e);
                }

            })).sheet().doRead();
        }catch (Exception e) {
            throw  new RRException(e.toString(),e);
        }

        ProgressSingleton.remove(id + "Progress");

        //查询数据库中重复的IMEI记录，返回对应记录。
        QueryWrapper<TClientInfoEntity> qImei = new QueryWrapper<>();
        qImei.select("client_id_card as imei");
        qImei.isNotNull("client_id_card");
        qImei.gt("len(client_id_card)",0);
        qImei.groupBy("client_id_card");
        qImei.having("count(*) > 1");
        List <Map<String, Object>> maps = tClientInfoService.listMaps(qImei);

        return R.ok().put("url",fileName).put("imei",maps);
    }



}
